import json

import sqlalchemy
from sqlalchemy.orm import session

from app.datatype.session import (
    SessionCreateMdl, Session, SessionUpdateMdl, SessionDeleteMdl, SessionListMdl,
)
from app.initializer import g
from app.utils import db_async



class SessionCreateBiz(SessionCreateMdl):

    async def create(self):
        async with g.db_async_session() as session:
            return await db_async.create(
                session=session,
                model=Session,
                data={
                    "session_name": self.session_name,
                    "user_id": self.user_id,
                }
            )

class SessionUpdateBiz(SessionUpdateMdl):

    async def update(self):
        async with g.db_async_session() as session:
            return await db_async.update(
                session=session,
                model=Session,
                data={
                    "session_name": self.session_name,
                    "is_top": self.is_top,
                },
                filter_by={"id": self.id},
            )

class SessionDeleteBiz(SessionDeleteMdl):
    async def delete(self):
        async with g.db_async_session() as session:
            return await db_async.update(
                session=session,
                model=Session,
                data={
                    "is_deleted": 1,
                },
                filter_by={"id": self.id},
            )

class SessionListBiz(SessionListMdl):
    async def lst(self):
        #查询 sessionList 通过userid order by created_at desc 并且非删除状态
        sql = sqlalchemy.text(f"SELECT id ,session_name ,user_id, created_at,updated_at ,is_top  FROM {Session.__tablename__} "
               f"WHERE user_id = :user_id AND is_deleted = 0 "
               f"ORDER BY is_top DESC , created_at DESC  ")
        async with g.db_async_session() as session:
            result = await session.execute(sql,{"user_id": self.user_id})
            rows = result.fetchall()
            field_names = list(SessionListMdl.__fields__.keys())
            return [SessionListMdl(**dict(zip(field_names, row))).dict() for row in rows]
